<template>
	<view class="container">
		<view class="example">
			<uni-forms ref="formRef" :model="user" :rules="rules" labelWidth="80px">
				<uni-forms-item label="用户昵称" name="nickname">
					<uni-easyinput v-model="user.nickname" placeholder="请输入昵称" />
				</uni-forms-item>
				<uni-forms-item label="手机号码" name="mobile">
					<uni-easyinput v-model="user.mobile" placeholder="请输入手机号码" />
				</uni-forms-item>
				<uni-forms-item label="邮箱" name="email">
					<uni-easyinput v-model="user.email" placeholder="请输入邮箱" />
				</uni-forms-item>
				<uni-forms-item label="性别" name="sex" required>
					<uni-data-checkbox v-model="user.sex" :localdata="sexs" />
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="submit">提交</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue';
	import { getUserProfile, updateUserProfile } from "@/api/system/user/profile";

	const formRef = ref();
	const user = ref<any>({
		nickname: "",
		mobile: "",
		email: "",
		sex: ""
	});
	const sexs = ref([
		{ text: '男', value: 1 },
		{ text: '女', value: 2 }
	]);
	const rules = ref({
		nickname: [{ required: true, message: '用户昵称不能为空' }],
		mobile: [
			{ required: true, message: '手机号码不能为空' },
			{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
		],
		email: [
			{ required: true, message: '邮箱地址不能为空' },
			{ type: 'email', message: '请输入正确的邮箱地址' }
		]
	});

	onMounted(async () => {
		await getUser();
	});

	const getUser = async () => {
		user.value = await getUserProfile();
	};

	const submit = async () => {
		try {
			await formRef.value.validate();
			await updateUserProfile(user.value);
			getUser()
			uni.showToast({ title: "修改成功", icon: "success" });
		} catch (error) {
			console.error("表单验证失败", error);
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #ffffff;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}
</style>